package com.tuanzi.blog.web.admin;

import com.tuanzi.blog.model.User;
import com.tuanzi.blog.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 雄关漫道真如铁，而今迈过从头越
 **/

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping
    public String loginPage(){
        System.out.println("我开始跳转了!!!");
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,@RequestParam String password,
                        HttpSession session,RedirectAttributes attributes){

        User user = userService.checkUser(username, password);

        if (user != null){
            //不要把密码传到前端
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        }else {
            //重定向返回
            attributes.addFlashAttribute("message","用户名或者密码使用错误!");
            //这个地方需要重定向到登录页面
            return "redirect:/admin";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){

        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
